<template>
  <div>
    <a-form
      :form="form"
      layout="inline"
      @submit.prevent="onSubmit"
      id="user-search"
      :style="{ marginBottom: '20px' }"
    >
      <a-row :gutter="20">
        <a-col :span="3">
          <a-form-item>
            <a-input
              placeholder="请输入姓名或者账号"
              v-decorator="['name']"
              allowClear
              ref="username"
            />
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-form-item>
            <a-select
              v-decorator="['province']"
              placeholder="省"
              allowClear
              @change="changeProvince"
              ref="province"
            >
              <a-select-option
                v-for="item in drd.province"
                :key="item.id"
                :value="item.id"
                >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-form-item>
            <a-select
              v-decorator="['city']"
              placeholder="市"
              allowClear
              @change="changeCity"
              ref="city"
            >
              <a-select-option
                v-for="item in drd.city"
                :key="item.id"
                :value="item.id"
                >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-form-item>
            <a-select
              v-decorator="['area']"
              placeholder="区"
              allowClear
              ref="area"
            >
              <a-select-option
                v-for="item in drd.area"
                :key="item.id"
                :value="item.id"
                >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-form-item>
            <a-select
              v-decorator="['roleId']"
              placeholder="角色"
              allowClear
              ref="roleId"
            >
              <a-select-option
                v-for="item in roles"
                :key="item.id"
                :value="item.id"
                >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-form-item>
            <!-- <a-tree-select v-decorator="['departmentId']"
                            treeDefaultExpandAll
                            :treeData="deps"
                            placeholder="归属部门"
                            allowClear
                        ></a-tree-select> -->
            <a-tree-select
              v-model="value"
              placeholder="归属部门"
              treeDefaultExpandAll
              :tree-data="deps"
              ref="keys"
              :replaceFields="replaceFields"
            >
            </a-tree-select>
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-form-item>
            <a-select
              v-decorator="['status']"
              placeholder="状态"
              allowClear
              ref="status"
            >
              <a-select-option value="1">可用</a-select-option>
              <a-select-option value="0">停用</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row style="margin-top: 15px">
        <a-form-item>
          <a-button type="primary" html-type="submit" @click="findinfo"
            >筛选</a-button
          >
        </a-form-item>
        <a-form-item style="margin-left: 20px">
          <a-button type="primary" icon="plus" @click="showCreate"
            >新增账号</a-button
          >
        </a-form-item>
      </a-row>
    </a-form>

    <a-table
      :columns="columns"
      :dataSource="tableData"
      rowKey="id"
      :pagination="pagination"
      :pageSize="pageSize"
      bordered
    >
      <span slot="action" slot-scope="text, record">
        <div class="delete-image">
          <a
            v-if="record.username === '--'"
            href="#"
            @click.stop.prevent="showModal(record, 'approval')"
          >
            <img src="./../../assets/images/approval.svg" alt="" />
          </a>
          <router-link :to="'/user/update/' + record.id">
            <img src="./../../assets/images/view.svg" alt="" />
          </router-link>
          <a href="#" @click.stop.prevent="showModal(record)">
            <img src="./../../assets/images/delete.svg" alt="" />
          </a>
        </div>
      </span>
    </a-table>

    <a-modal
      v-model="showcreate"
      title="新增账号"
      @ok="createSubmit"
      @cancel="cancel"
      centered
      :cancelButtonProps="{ props: { type: 'primary' } }"
      :keyboard="false"
      okText="确认"
      :maskClosable="false"
      destroyOnClose
      :afterClose="createAfterClose"
    >
      <create
        :deps="deps"
        :roles="roles"
        :id="deleteRow.username === '--' ? deleteRow.id || '' : ''"
        ref="create"
        @getList="getList"
        @toRegisteredStep="toRegisteredStep"
        @toUseRegistered="toUseRegistered"
        @hideCreate="hideCreate"
        @showtost="controltost"
      >
      </create>

      <a-modal title="提示信息" :visible="istost" :closable="false">
        <p>请把表单信息按要求填写完整！！</p>
        <template slot="footer">
          <a-button type="primary" @click="istost = false">确定</a-button>
        </template>
      </a-modal>
    </a-modal>

    <a-modal
      v-model="useRegistered"
      title="登录"
      width="450px"
      centered
      @cancel="
        () => {
          loginForm.resetFields();
          form.resetFields();
        }
      "
      :keyboard="false"
      :maskClosable="false"
    >
      <a-form :form="loginForm">
        <a-form-item
          label="账号"
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 20 }"
        >
          <a-input
            v-decorator="[
              'center_username',
              { rules: [{ required: true, message: '请输入账号！' }] },
            ]"
            @focus="() => (this.readonly = false)"
            :read-only="readonly"
            placeholder="请输入账号"
          />
        </a-form-item>
        <a-form-item
          label="密码"
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 20 }"
        >
          <a-input
            v-decorator="[
              'center_password',
              { rules: [{ required: true, message: '请输入密码！' }] },
            ]"
            @focus="() => (this.readonly = false)"
            :read-only="readonly"
            type="password"
            placeholder="请输入密码"
          />
        </a-form-item>
        <transition name="slide-fade">
          <p class="tips" v-if="errorShow">{{ errMsg }}</p>
        </transition>
      </a-form>
      <template slot="footer">
        <a-button @click="checkUser" type="primary">下一步</a-button>
      </template>
    </a-modal>

    <a-modal
      v-model="show_delete"
      title="删除账号"
      @ok="handleDelete"
      width="450px"
      :cancelButtonProps="{ props: { type: 'primary' } }"
      centered
      :keyboard="false"
      okText="删除"
      :maskClosable="false"
    >
     
        <p>是否删除此账号？</p>
      <template slot="footer">
        <a-button type="warning" @click="show_delete=false">取消</a-button>
        <a-button type="primary" @click="handleDelete">确定</a-button>
    </template>
    </a-modal>

    <a-modal
      v-model="show_approval"
      title="审批用户"
      closeIcon
      :closable="false"
      :cancelButtonProps="{ props: { type: 'primary' } }"
      centered
      :keyboard="false"
      :maskClosable="false"
    >
      <template slot="footer">
      <div class="footer-wrap">
          <a-button type="warning" @click="show_approval = false">取消</a-button>
        <a-button type="danger" @click="handleApproval(-1)">拒绝</a-button>
        <a-button type="primary" @click="handleApproval(1)">确定</a-button>
      </div>
      </template>

      <div class="confirm-delete-wrapper">
        <p>是否审批通过此账号？</p>
      </div>
    </a-modal>
  </div>
</template>

<script>
import axios from "axios";
import { mapActions } from "vuex";

import Create from "./create";
export default {
  components: { Create },
  data() {
    return {
      pageSize: 10,
      pagination: {
        current: 1,
        total: 0,
        pageSize: 10,
        showQuickJumper: true,
        onChange: (page, size) => {
          this.handleChange(page, size);
        },
      },
      keywords: "",
      tableData: [],
      test: [
        {
          title: "Node1",
          value: "0-0",
          key: "0-0",
          children: [
            {
              title: "Child Node1",
              value: "0-0-1",
              key: "0-0-1",
            },
            {
              title: "Child Node2",
              value: "0-0-2",
              key: "0-0-2",
            },
          ],
        },
        {
          title: "Node2",
          value: "0-1",
          key: "0-1",
        },
      ],
      value: undefined,
      columns: [
        { title: "账号", dataIndex: "username", align: "center", width: "10%" },
        { title: "姓名", dataIndex: "name", align: "center", width: "10%" },
        {
          title: "归属部门",
          dataIndex: "departmentName",
          align: "center",
          width: "15%",
        },
        { title: "角色", dataIndex: "roleName", align: "center", width: "15%" },
        { title: "手机号", dataIndex: "phone", align: "center", width: "15%" },
        {
          title: "账号状态",
          dataIndex: "statusName",
          align: "center",
          width: "15%",
        },
        {
          title: "操作",
          scopedSlots: { customRender: "action" },
          align: "center",
          width: "10%",
        },
      ],
      form: this.$form.createForm(this),
      showcreate: false,
      show_delete: false,
      show_approval: false,
      deleteRow: {},
      deps: [],
      roles: [],
      drd: {
        province: [],
        city: [],
        area: [],
      },
      
      
      //控制提示信息
      istost: false,
      useRegistered: false,
      loginForm: this.$form.createForm(this),
      errorShow: false,
      readonly: true,
      username: "",
      replaceFields: {
        title: "name",
        key: "id",
        value: "id",
      },
    };
  },
  async mounted() {
    await this.getList();
    this.getDstrict("province");
    this.getDepartment();
    this.http("get", "/role/all").then((res) => {
      this.roles = res.data || [];
    });
  },
  methods: {
    //打开提示信息
    controltost() {
      this.istost = true;
    },
    //筛选
    async findinfo() {
      let [name, province, city, area, roleId, departmentId, status] = [
        this.$refs.username.value,
        this.$refs.province.value,
        this.$refs.city.value,
        this.$refs.area.value,
        this.$refs.roleId.value,
        this.$refs.keys.value,
        this.$refs.status.value,
      ];
      console.log([name, province, city, area, roleId, departmentId, status]);

      let {
        data: { data, totalCount },
      } = await this.http("get", "/user/selectLikeList", {
        name,
        province,
        city,
        area,
        roleId,
        departmentId,
        status,
      });
      this.tableData = (data || []).map((item) => {
        return {
          ...item,
          username: item.username ? item.username : "--",
        };
      });
      this.pagination.total = totalCount;
    },
    async getList(param = {}) {
      let req = {
        pageSize: this.pagination.pageSize,
        pageNo: this.pagination.current,
      };

      let {
        data: { data, totalCount },
      } = await this.http(
        "get",
        "/user/selectLikeList",
        Object.assign(req, param)
      );
      this.tableData = (data || []).map((item) => {
        return {
          ...item,
          username: item.username ? item.username : "--",
        };
      });
      this.pagination.total = totalCount;
    },
    async getDstrict(type, pid) {
      let { data } = await this.http("get", "/dstrict/list", { pid });
      this.drd[type] = data || [];
    },
    changeProvince(val) {
      this.form.resetFields(["city", "area"]);
      this.drd.city = [];
      this.drd.area = [];
      if (val) {
        this.getDstrict("city", val);
      }
    },
    changeCity(val) {
      this.form.resetFields(["area"]);
      this.drd.area = [];
      if (val) {
        this.getDstrict("area", val);
      }
    },
    async getDepartment() {
      let { data } = await this.http("get", "/department/tree");

      this.deps = data;
    },
    createTree(data) {
      let tree = [];
      data.map((item) => {
        let { name, id } = item;
        item.label = name;
        item.value = id;
        item.children = data.filter((f) => f.pid == item.id);
        if (item.pid === 0 && item.children.length) {
          tree.push(item);
        }
      });
      return tree;
    },
    onSubmit() {
      //搜索提交
      this.form.validateFields((err, values) => {
        values = { ...values, ...{ username: values.user_no } };
        delete values.user_no;
        if (!err) {
          this.pagination.current = 1;
          this.getList(values);
        }
      });
    },
    cancel() {
      this.$refs.create.form.resetFields();
      this.storeAccountInfo({});
    },
    showCreate() {
      this.showcreate = true;
      this.deleteRow = {};
    },
    hideCreate() {
      this.showcreate = false;
    },
    createAfterClose() {
      this.deleteRow = {};
    },
    showModal(row, type) {
      if (type === "approval") {
        this.show_approval = true;
      } else {
        this.show_delete = true;
      }
      this.deleteRow = row;
    },
    async handleApproval(type) {
      if (type == -1) {
        let { id } = this.deleteRow;
        let { status, message, data } = await this.http(
          "get",
          `/user/refuse/${id}`
        );
        if (status === 1) {
          this.$message.success("拒绝成功", 1);
          this.getList();
        } else {
          this.$message.error(message, 1);
        }
        this.show_approval = false;
      } else {
        this.show_approval = false;
        this.showcreate = true;
        // let { id } = this.deleteRow;
      }
    },
    createSubmit() {
      //新增提交
      this.$refs.create.onSubmit();
    },

    checkUser(e) {
      e.preventDefault();

      this.loginForm.validateFields(async (err, values) => {
        if (!err) {
          await this.http("post", "user/usercenter-login", {
            username: values.center_username,
            password: values.center_password,
          }).then(async (res) => {
            if (parseInt(res.code) === 0) {
              this.openid = res.data.openid;
              this.token = res.token;
              this.loginForm.resetFields();

              let filledData = {
                username: values.center_username,
                password: values.center_password,
                password_rep: values.center_password,
                mobile: res.data.phone,
                realname: res.data.name,
              };
              this.storeAccountInfo(filledData);
              await this.form.setFieldsValue(filledData);
              this.useRegistered = false;
              // await this.$nextTick(() => {this.$emit('toRegisteredStep', true)})
            } else {
              this.errorShow = true;
              this.errMsg = res.msg;
              setTimeout(() => {
                this.errorShow = false;
              }, 3000);
            }
          });
        }
      });
    },

    handleChange(page, size) {
      this.pagination.current = page;
      this.pagination.pageSize = size;
      this.getList();
    },
    async handleDelete() {
      let that = this;
      let row = this.deleteRow;
      let { status, message } = await that.deleteData(row.id);
      if (status === 1) {
        that.$message.success("删除成功", 1);
        that.getList();
      } else {
        that.$message.error(message, 1);
      }
      this.show_delete = false;
    },
    async deleteData(id) {
      return await this.http("delete", `/user/delete/${id}`);
    },
    toRegisteredStep(bool) {
      this.showcreate = bool;
    },
    toUseRegistered(bool) {
      console.log(bool);
      this.useRegistered = bool;
    },
    ...mapActions(["storeAccountInfo"]),
  },
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
#user-search {
  .ant-input {
    width: 172px;
  }

  .ant-select {
    width: 137px;
  }
}

.confirm-delete-wrapper {
  width: 100%;
  padding: 20px;
  text-align: center;
  p {
    font-size: 16px;
  }
}

@media screen and (max-width: 1366px) {
  #user-search {
    .ant-input {
      width: 107px;
    }

    .ant-select {
      width: 107px;
    }
  }
}

::v-deep {
  .ant-modal-body {
    max-height: 600px;
    overflow-y: auto;
  }
  .ant-modal-footer {
    margin: 0;
  }
}
.footer-wrap{
  display: flex;
  justify-content: center;
  
}
</style>
